package com.ve.c51;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ve.bluetooth.BluetoothSerialAdapter;
import com.ve.bluetooth.BluetoothService;
import com.ve.bluetooth.BluetoothStatus;
import com.ve.bluetooth.ConnectListener;
import com.ve.bluetooth.ScanListener;
import com.ve.c51.base.BaseActivity;
import com.ve.usb.SerialHelper;
import com.ve.usb.SerialService;
import com.ve.usb.UsbSerialAdapter;
import com.ve.utils.PermissionsUtils;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;

public class SelectTargetActivity extends BaseActivity {

    private RecyclerView targetList;
    private TargetAdapter targetAdapter;
    private SwipeRefreshLayout refreshLayout;

    private BaseTarget target;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_target);
        initToolbar(R.id.activity_target_toolbar);
        if (getIntent().getBooleanExtra("isWire",true)) {
            target=new UsbTarget();
            setTitle("Usb列表");
        }else {
            target = new BluetoothTarget();
            setTitle("蓝牙列表");

        }

        refreshLayout = findViewById(R.id.activity_target_refresh);
        targetList = findViewById(R.id.activity_target_list);

        targetAdapter = new TargetAdapter();
        targetAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            TargetBean item = (TargetBean) adapter.getItem(position);
            target.choose(position, item.getNode());
        });
        targetList.setAdapter(targetAdapter);
        targetList.setLayoutManager(new LinearLayoutManager(this));
        refreshLayout.setOnRefreshListener(() -> target.load());


        target.create();
        if (PermissionsUtils.hasPermissions(this,target.requirePermissions())){
            target.load();
        }else {
            requestPermissions(target.requirePermissions(), 777);
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode==777){
            target.load();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        target.destroy();

    }

    public static void start(Context context, boolean wire) {
        Intent intent = new Intent(context, SelectTargetActivity.class);
        intent.putExtra("isWire",wire);
        context.startActivity(intent);
    }

    public interface BaseTarget {
        String[] requirePermissions();

        void create();

        void destroy();

        void load();

        void choose(int position, Object item);

    }
    class UsbTarget implements BaseTarget{

        SerialService serialService;
        @Override
        public String[] requirePermissions() {
            return new String[0];
        }

        @Override
        public void create() {
            serialService=SerialService.getInstance();
        }

        @Override
        public void destroy() {

        }

        @Override
        public void load() {
            UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
            HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
            for (String name : deviceList.keySet()) {
                UsbDevice device=deviceList.get(name);
                String info="vendorId="+device.getDeviceId()+ " productId="+device.getProductId();
                targetAdapter.addData(new TargetBean(device.getDeviceName(),info,device));
            }
        }

        @Override
        public void choose(int position, Object item) {
            UsbDevice device= (UsbDevice) item;
            if (!SerialService.isSerialDevice(device)) {
                Toast.makeText(SelectTargetActivity.this, "不支持的设备", Toast.LENGTH_SHORT).show();
                return;
            }
            serialService.runWithPermission(device,() -> {
               serialService.open(device);
                UsbSerialAdapter serialAdapter=new UsbSerialAdapter(serialService);
                serialAdapter.setName(device.getDeviceName());
                serialAdapter.setBluetooth(false);
                EventBus.getDefault().post(serialAdapter);
                finish();

            });


        }
    }

     class BluetoothTarget implements BaseTarget, ConnectListener, ScanListener {
        private BroadcastReceiver mReceiver;
        private BluetoothService service;
        private BluetoothAdapter bluetoothAdapter;

        @Override
        public String[] requirePermissions() {
            return BluetoothService.NEEDED_PERMISSIONS;
        }

        @Override
        public void create() {
            mReceiver = BluetoothService.createAutopairReceiver("1234");
            service = BluetoothService.getDefaultInstance();
            service.setOnScanCallback(this);
            service.setOnEventCallback(this);

            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            registerReceiver(mReceiver, new IntentFilter(BluetoothService.ACTION_PAIRING_REQUEST));
        }

        @Override
        public void destroy() {
            unregisterReceiver(mReceiver);
        }

        @Override
        public void load() {
            if (bluetoothAdapter.isEnabled()) {
                targetAdapter.clear();
                service.startScan();
            } else {
                refreshLayout.setRefreshing(false);
                bluetoothAdapter.enable();
                Toast.makeText(getApplicationContext(), "正在打开蓝牙", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void choose(int position, Object item) {
            service.connect((BluetoothDevice) item);
            service.stopScan();
            Toast.makeText(SelectTargetActivity.this, "连接中", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onDeviceDiscovered(BluetoothDevice device, int rssi) {
            TargetBean targetBean = new TargetBean(device.getName() == null ? device.getAddress() : device.getName(), device.getAddress(), device);
            targetBean.setRssi(rssi);
            targetAdapter.addData(targetBean);
        }

        @Override
        public void onStartScan() {
            refreshLayout.setRefreshing(true);
        }

        @Override
        public void onStopScan() {
            refreshLayout.setRefreshing(false);
        }


        @Override
        public void onStatusChange(BluetoothStatus status) {

        }

         @Override
         public void onConnected(BluetoothDevice device) {
             BluetoothSerialAdapter serialAdapter=new BluetoothSerialAdapter(service);
             serialAdapter.setBluetooth(true);
             serialAdapter.setName(device.getName() == null ? device.getAddress() : device.getName());
             EventBus.getDefault().post(serialAdapter);
             finish();
         }

        @Override
        public void onToast(String message) {
            Toast.makeText(SelectTargetActivity.this, message, Toast.LENGTH_SHORT).show();
        }


     }



    private class TargetBean {
        String name;
        String detail;
        Object node;

        int rssi;

        public TargetBean(String name, String detail, Object node) {
            this.name = name;
            this.detail = detail;
            this.node = node;
        }

        public TargetBean(String name, String detail) {
            this.name = name;
            this.detail = detail;
        }

        public String getName() {
            return name;
        }

        public String getDetail() {
            return detail;
        }

        public Object getNode() {
            return node;
        }

        public int getRssi() {
            return rssi;
        }

        public void setRssi(int rssi) {
            this.rssi = rssi;
        }
    }

    private class TargetAdapter extends BaseQuickAdapter<TargetBean, BaseViewHolder> {

        public TargetAdapter() {
            super(R.layout.item_target, new ArrayList<>());
        }

        @Override
        protected void convert(BaseViewHolder helper, TargetBean item) {
            helper.setText(R.id.item_target_name, item.getName());
            helper.setText(R.id.item_target_detail, item.getDetail());
            helper.setText(R.id.item_target_rssi,"信号强度:"+ item.getRssi());
            helper.addOnClickListener(R.id.item_target_root);
        }

        public void clear() {
            getData().clear();
            notifyDataSetChanged();
        }
    }


}
